<template>
    <n-scrollbar x-scrollable style="max-height: 100vh">
        <CommonPage>
            <div>
                <n-form ref="form"
                        :model="searchCondition"
                        label-placement="left"
                        label-align="right"
                        label-width="80px"
                        :show-require-mark="false">
                    <div>
                        <div class="grid md:flex md:flex-wrap md:gap-x-1">

                            <n-form-item style="margin-left: 10px">
                                <label style="width: 70px;">活动名称：</label>
                                <n-input style="width: 170px;" v-model:value="searchCondition.name" placeholder="请输入当前分类名称" clearable/>
                            </n-form-item>
                            <n-form-item style="margin-left: 10px">
                                <label style="width: 80px;">活动店铺:</label>
                                <n-select v-model:value="searchCondition.adminId" :options="admins" />
                            </n-form-item>
                            <n-form-item  style="margin-left: 10px">
                                <n-button type="primary" @click="searchByCondition">筛选</n-button>
                            </n-form-item>
                            <n-form-item  style="margin-left: 10px">
                                <n-button type="primary" @click="showForm = true">添加活动</n-button>
                            </n-form-item>
                            <n-form-item  style="margin-left: 10px">
                                <n-button type="error" @click="deleteSelectProduct">批量删除</n-button>
                            </n-form-item>

                        </div>
                    </div>
                </n-form>
            </div>
            <AddCategoryForm :option="option" @update-page="searchByCondition" :show="showForm" :onClose="handleClose" />
            <n-data-table
                    remote
                    :single-line="false"
                    ref="table"
                    :columns="columns"
                    :data="categoryList"
                    :loading="loading"
                    :pagination="paginationReactive"
                    :row-key="rowKey"
                    :scroll-x="900"
                    @update:checked-row-keys="handleCheck"
            />
        </CommonPage>
    </n-scrollbar>
</template>

<script setup>
    import {onMounted, reactive, ref} from 'vue'
    import api from '@/api/admin';

    import {useUserStore} from '@/store';
    import {useRouter} from 'vue-router';

    import {NButton, NCascader} from 'naive-ui'


    const showForm = ref(false);
    const handleClose = () => {
        showForm.value = false;
    };
    const userStore = useUserStore()
    const router = useRouter()
    const loading = ref(true)
    const categoryList = ref([])
    const range = ref(null)
    const value = ref("全部")
    const checkedRowKeysRef = ref([]);
    const option = ref([
    ])
    const searchCondition = ref({
        adminId: -1,
        parentCategoryName: "",
        name: ""
    });
    const admins = ref([])
    admins.value.push({
        label:'全部',
        value:-1,
    })
    const columns = [
        {
            type: 'selection',
            fixed: 'left',
        },
        {
            key: 'colId',
            title: '序号',
            width: 60,
        },
        {
            key: 'name',
            title: '活动名称',
            width: 100,
        },
        {
            key: 'createTime',
            title: '创建时间',
            width: 100,
            align:'left',
        },
        {
            key: 'startTime',
            title: '开始时间',
            width: 100,
            align:'left',
        },
        {
            key: 'endTime',
            title: '结束时间',
            width: 100,
            align:'left',
        },
        {
            key: 'rule',
            title: '活动规则',
            width: 100,
            align:'left',
        },
        {
            key: 'storeCommodityName',
            title: '活动产品',
            width: 100,
            align:'left',
        },
        {
            key: 'shopName',
            title: '活动店铺',
            width: 100,
            align:'left',
        },
        {
            key: 'promotionRate',
            title: '活动折扣',
            width: 100,
            align:'left',
        },
        {
            key: 'operation',
            title: '操作',
            width: 100,
            render(row) {
                return h(
                    CategoryActions,
                    {
                        onClickDelete: () => onDeleteProductCategory(row),
                        onClickEdit: () => onEditProductCategory(row),
                    }
                );
            }
        },
    ]
    let total = 0
    const paginationReactive = reactive({
        page: 1,
        pageSize: 20,
        showSizePicker: true,
        pageSizes: [20, 50, 100],
        itemCount:0,
        prefix: () => {
            return '查询出 ' + total + '条记录';
        },
        onChange: (page) => {
            paginationReactive.page = page;
            queryByPage()
        },
        onUpdatePageSize: (pageSize) => {
            paginationReactive.pageSize = pageSize;
            paginationReactive.page = 1;
            queryByPage()
        }
    });
    const handleCheck = (rowKeys) => {
        checkedRowKeysRef.value = rowKeys;
    }
    const deleteSelectProduct = () => {
        if(checkedRowKeysRef.value.length <= 0) {
            $message.error("当前并未选择产品！")
            return
        }
        $dialog.confirm({
            title: '警告',
            content: '您确定删除当前所选产品？',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: async () => {
                const ids = checkedRowKeysRef.value.join(",")
                loading.value = true
                try {
                    const res = await api.deleteProductCategories({params:{ids}})
                    if(res.code === 200) {
                        $message.success("删除所选产品成功！")
                        await searchByCondition()
                    }
                    else {
                        $message.error(res.message)
                    }
                } catch (err) {
                    $message.error("删除所选产品失败！")
                }finally{
                    loading.value = false
                }
            },
        })
    }
    const searchByCondition = async () => {
        loading.value = true
        try {
            paginationReactive.page = 1;
            const res = await api.findPageProductCategory({
                params: {
                    adminId: searchCondition.value.adminId.toString(),
                    parentCategoryName: searchCondition.value.parentCategoryName,
                    name: searchCondition.value.name,
                    pageNum: paginationReactive.page,
                    pageSize: paginationReactive.pageSize,
                }
            })
            if(res.code === 200) {
                total = res.data.total
                paginationReactive.itemCount = total
                const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
                categoryList.value = res.data.records.map((item,i)=>{
                    return {...item,
                        colId: baseCount + i + 1,
                    }
                })
            }
            else {
                $message.error(res.message)
            }
        } catch (err) {
            $message.error("查询产品失败！")
        }finally{
            loading.value = false
        }
    }
    const exportListInfo = async () => {
        const res = await api.exportProductCategoryList({
            adminId: searchCondition.value.adminId
        })
        const contentDisposition = res.headers["content-disposition"]
        // console.log(res)
        let original_fileName = ""
        if(contentDisposition) {
            const uri = res.headers["content-disposition"].split("=")[1]
            original_fileName = window.decodeURI(uri)
        }
        const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
        if(window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, original_fileName);
        } else{
            const fileName = original_fileName;
            const elink = document.createElement('a')
            document.body.appendChild(elink)
            elink.download= fileName;
            elink.style.display ="none"
            elink.href  = window.URL.createObjectURL(blob)
            elink.click()
            window.URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
        }
    }
    const onDeleteProductCategory = async (productCategory) => {
        $dialog.confirm({
            title: '警告',
            content: '您确定删除当前产品？',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: async () => {
                const {id} = productCategory
                loading.value = true
                try {
                    const res = await api.deleteProductCategory({id})
                    if(res.code === 200) {
                        $message.success("删除产品成功！")
                        await searchByCondition()
                    }
                    else {
                        $message.error(res.message)
                    }
                } catch (err) {
                    $message.error("删除产品失败！")
                }finally{
                    loading.value = false
                }
            }
        })
    }
    const onEditProductCategory = async (productCategory) => {
        const {id} = productCategory
        await router.push({name: 'AdminLogDetail', params: {productCategoryId: id}});
    }
    const queryByPage = async () => {
        loading.value = true
        try {
            const res = await api.findPageProductCategory(
                {
                    params:{
                        pageNum:paginationReactive.page,
                        pageSize:paginationReactive.pageSize,
                    }
                })
            if(res.code === 200) {
                total = res.data.total
                paginationReactive.itemCount = total
                const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
                categoryList.value = res.data.records.map((item,i)=>{
                    return {...item,
                        colId: baseCount + i + 1,
                    }
                })
                // 调用函数生成n-cascader的options
                convertToCascaderOptions(res.data.records);
            }
            else {
                $message.error(res.message)
            }
        } catch (err) {
            $message.error("获取产品失败！")
        }finally{
            loading.value = false
        }
    }
    const queryAdminList = async () => {
        loading.value = true
        try {
            const res = await api.findAdminsInProductCategory()
            if(res.code === 200) {
                res.data.map((item)=>{
                    admins.value.push({
                        label: item.name,
                        value: item.id
                    })
                })
            }
            else {
                $message.error(res.message)
            }
        } catch (err) {
            $message.error("获取管理员信息失败！")
        }finally{
            loading.value = false
        }
    }
    const convertToCascaderOptions = (flatData) => {
        console.log(flatData)
        const idNodeMap = {}; // 用于映射id到对应的节点对象
        const opt = []; // 最终生成的级联选择器数据

        // 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
        flatData.forEach(node => {
            idNodeMap[node.id] = { ...node, children: [] };
        });
        // 构建树形结构
        Object.values(idNodeMap).forEach(node => {
            if (node.parentCategoryId === null) {
                // 如果parentId为null，则该节点是根节点
                opt.push(node);
            } else {
                // 否则，将该节点添加到其父节点的children数组中
                const parentNode = idNodeMap[node.parentCategoryId];
                if (parentNode) {
                    parentNode.children.push(node);
                }
            }
        });
        console.log(opt)
        // 遍历并转换所有根节点
        option.value = opt.map(node=>{
            return traverse(node)
        });
    }
    // 转换数据结构为n-cascader所接受的格式（将name和parentName转换为label，并移除不必要的字段）
    const traverse = (node) => {
        const { id, name, children} = node;
        return {
            value: id.toString(), // n-cascader通常要求value为字符串
            label: name,
            children: children.map(child => traverse(child)), // 递归处理子节点
        };
    }
    // 使用optionsForNCascader作为n-cascader的options
    const rowKey = (rowData) => {
        return rowData.id
    }
    onMounted(()=>{
        queryAdminList()
        queryByPage()
    })
</script>
<style scoped>
    :deep(.n-data-table-th__title),
    :deep(.n-data-table-td) {
        text-align: center;

    }
    :deep(.n-select) {
        width: 120px !important;
    }

    :deep(.two-line-description) {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 控制显示的行数 */
        overflow: hidden;
    }
</style>
